import err from './error.js'
import msg from './massage.js'

const requestUtils = {
  get (url = '', data = {}, header = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: url,
        data: data,
        header: header,
        method: 'GET',
        success: (res) => {
          resolve(res.data)
        },
        fail: (e) => {
          reject(err('REQUEST_ERROR', e))
        }
      })      
    })
  },
  
  post (url = '', data = {}, header = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: url,
        data: data,
        header: header,
        method: 'POST',
        success: (res) => {
          resolve(res.data)
        },
        fail: (e) => {
          reject(err('REQUEST_ERROR', e))
        }
      })      
    })
  },
  
  // 调用云函数，最原始的版本
  cloud (name = '', data = {}) {
    return new Promise((resolve, reject) => {
      uniCloud.callFunction({
        name,
        data
      })
      .then((res, reqId) => {
        if (res.result.code === 0) {
          resolve(res.result)
        }
        else {
          reject(err('CLOUD_FUNC_ERROR', res.result))
        }
      })
      .catch((e) => {
        reject(err('CLOUD_FUNC_ERROR', e))
      })
    })
  }
}

export default requestUtils